package reverseSentence;

import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;
import java.util.Stack;

/**
 * 牛客最近来了一个新员工Fish，每天早晨总是会拿着一本英文杂志，写些句子在本子上。
 * 同事Cat对Fish写的内容颇感兴趣，有一天他向Fish借来翻看，但却读不懂它的意思。
 * 例如，“student. a am I”。后来才意识到，这家伙原来把句子单词的顺序翻转了，正确的句子应该是“I am a student.”。
 * Cat对一一的翻转这些单词顺序可不在行，你能帮助他么？
 *
 *
 * */
public class Solution {

    public String reverseSentence(String in ){
        StringBuilder sb = new StringBuilder();
        if(in.length() == 0 || in.trim().length() == 0 ){
            return in ;
        }
        String[] s = this.split2(in," ");
        for(int i = s.length -1 ; i >=0 ; i--){
            sb.append(s[i] + " ");
        }
        return sb.toString();
    }
    private String[] split(String in , String delimer){
        Stack<Character> s = new Stack<>();
        char[] chs = in.toCharArray();
        List<String> rs =  new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ; i < chs.length ; i++){
            if(chs[i] != ' ' || 0 == i){
                s.push(chs[i]);
            }else {
                while(!s.empty()){
                    sb.append(s.pop());
                }
                rs.add(this.reverse(sb.toString()));
                sb.delete(0,sb.length());
            }
        }
        while(!s.empty()){
            sb.append(s.pop());
        }
        rs.add(sb.toString());
        sb.delete(0,sb.length());
        return rs.toArray(new String[]{new String()});
    }
    public String[] split2(String in , String delimer){
        char[] chs = in.toCharArray();
        List<String> rs = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ; i < chs.length ; i++){
            if(chs[i] != ' ' || i == chs.length -1){
                sb.append(chs[i]);
            }else{
                rs.add(sb.toString());
                sb.delete(0,sb.length());
            }
        }
        if(sb.length() > 0){
            rs.add(sb.toString());
        }
        return rs.toArray(new String[]{});
    }

    public String reverse(String in ){
        char[] chs = in.toCharArray();
        StringBuilder sb = new StringBuilder();
        for(int i = chs.length-1;i>=0 ; i-- ){
            sb.append(chs[i]);
        }
        return sb.toString();
    }
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.reverseSentence("student. a am I"));
    }
}
